<?php

namespace app\api\controller;

use app\admin\model\Extension;
use app\admin\model\Video;
use app\common\controller\Api;
use app\common\library\Ems;
use app\common\library\Sms;
use fast\Date;
use fast\Random;
use think\Config;
use think\Db;
use think\Exception;
use think\Validate;
use \app\common\model\User as UserModel;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['login', 'mobilelogin', 'register', 'resetpwd', 'changeemail', 'changemobile', 'third'];
    protected $noNeedRight = '*';


    public function _initialize()
    {
        parent::_initialize();

        if (!Config::get('fastadmin.usercenter')) {
            $this->error(__('User center already closed'));
        }

    }

    /**
     * 会员中心
     */
    public function index()
    {
        $this->success('', ['welcome' => $this->auth->nickname]);
    }

    /**
     * 会员登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="account", type="string", required=true, description="账号")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     */
    public function login()
    {
        $account = $this->request->post('account');
        $password = $this->request->post('password');
        if (!$account || !$password) {
            $this->error(__('Invalid parameters'));
        }
        $ret = $this->auth->login($account, $password);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 手机验证码登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function mobilelogin()
    {
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (!Sms::check($mobile, $captcha, 'mobilelogin')) {
            $this->error(__('Captcha is incorrect'));
        }
        $user = \app\common\model\User::getByMobile($mobile);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            $ret = $this->auth->direct($user->id);
        } else {
            $ret = $this->auth->register($mobile, Random::alnum(), '', $mobile, []);
        }
        if ($ret) {
            Sms::flush($mobile, 'mobilelogin');
            $data = ['userinfo' => $this->auth->getUserinfo()];
            $this->success(__('Logged in successful'), $data);
        } else {
            $this->error($this->auth->getError());
        }
    }

    /**
     * 注册会员
     *
     * @ApiMethod (POST)
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="password", type="string", required=true, description="密码")
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="code", type="string", required=true, description="验证码")
     */
    public function register()
    {
        $chang = config('site.num_long');
        $duan = config('site.num_short');

        $username = $this->request->post('username');
        $username = 'Panda_' . $this->checkUsername($username);
        $password = $this->request->post('password');
        if (empty($password)) $password = '123456';

        //start 检查是否电报登录
        $telegram = $this->request->post('telegram');
        $last_name = $this->request->post('last_name');
        $first_name = $this->request->post('first_name');
        $hash = $this->request->post('hash');

        if ($username && $telegram && $last_name && $first_name && $hash) {
            //todo 验证hash
            $ret = $this->auth->login($username);
            if ($ret) {
                $data = ['userinfo' => $this->auth->getUserinfo()];
                $this->success(__('Logged in successful'), $data, 200);
            }
        }
        //end

        $mobile = $this->request->request('mobile');
        $invite_code = $this->request->request('invite_code');
        $avatars = array("1_1588736866.jpg", "2_1588736906.jpg", "3_1588736916.jpg", "4_1588736927.jpg", "5_1588736939.jpg", "7_1588737044.jpg", "8_1588737058.jpg", "10_1588737071.jpg", "11_1588737096.jpg", "12_1588737120.jpg", "13_1588737130.jpg", "14_1588737138.jpg", "15_1588737244.jpg", "16_1588737259.jpg", "17_1588737267.jpg", "18_1588737279.jpg", "19_1588737290.jpg", "20_1588737303.jpg", "21_1588740537.jpg", "22_1588740556.jpg", "23_1588740572.jpg", "24_1588740586.jpg", "26_1588741401.jpg", "27_1588741443.jpg", "28_1588741455.jpg", "29_1588741475.jpg", "31_1588741495.jpg", "32_1588741508.jpg", "33_1588741526.jpg", "34_1588741536.jpg", "35_1588741549.jpg", "36_1588741559.jpg", "37_1588741571.jpg", "38_1588741586.jpg", "39_1588741596.jpg", "40_1588741605.jpg", "41_1588741614.jpg", "42_1588741624.jpg", "43_1588741635.jpg", "44_1588741645.jpg", "45_1588741657.jpg", "46_1588741666.jpg", "47_1588741676.jpg", "48_1588741687.jpg", "49_1588741697.jpg", "50_1588741707.jpg");
        $avatar = $avatars[array_rand($avatars)];
        $numeber = $this->creatInvCode();
        $photo = '';// Code::c_qrcode('http://www.demo.com', time());
        $extends = [
            'number' => $numeber,
            'avatar' => '/mrtx/' . $avatar,
            'photo' => $photo,
            'num_long' => $chang,
            'num_short' => $duan,
            'uuid' => $this->request->request('uuid'),
            'telegram' => $telegram,
            'last_name' => $last_name,
            'first_name' => $first_name
        ];
        if ($last_name && $first_name) {
            $extends['nickname'] = $last_name . $first_name;
        }

        if (!$username || !$password) {
            $this->error(__('Invalid parameters'));
        }
        if ($mobile && !Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        $ret = $this->auth->register($username, $password, '', $mobile, $extends);
        if ($ret) {
            $data = ['userinfo' => $this->auth->getUserinfo()];
            if (!empty($invite_code)) {

                $pid = Usermodel::where('number', $invite_code)->value('id');//邀请人的数据

                Usermodel::where('id', $data['userinfo']['id'])->update(['pid' => $pid]);

                $this->rebate($invite_code, $data['userinfo']['id']);
                //$this->success(__('Sign up successful'), $data);
            }
            $this->success(__('Sign up successful'), $data, 200);
        } else {
            $this->error($this->auth->getError());
        }
    }//推广码

    /** 延迟处理邀请关系
     * @return void
     */
    public function invite_relation()
    {

        $invite_code = $this->request->param('invite_code');

        if (!empty($invite_code)) {

           $_pid = Usermodel::where('id',  $this->auth->id)->value('pid');
           if($_pid){
               $this->error('关系已存在');
           }
            $pid = Usermodel::where('number', $invite_code)->value('id');//邀请人的数据

            Usermodel::where('id',  $this->auth->id)->update(['pid' => $pid]);

            $this->rebate($invite_code,  $this->auth->id);
            $this->success('ok');
        }else{
            $this->error(__('Invalid parameters'));
        }
    }
    public function creatInvCode()
    {
        $code = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ";
        $arr = [];
        for ($i = 0; $i < 6; $i++) {
            $arr[$i] = $code[mt_rand(0, 35)];
        }
        $code = implode('', $arr);
        $number = usermodel::where('number', $code)->find();
        if ($number) {
            $code = $this->creatInvCode();
        }
        return $code;
    }

    public function checkUsername($username)
    {
        if (empty($username)) {
            $username = $this->creatInvCode();
        } else {
            $n = usermodel::where('username', $username)->count();

            if ($n) {
                $username = $this->creatInvCode();
            }
        }
        return $username;
    }
    //推广返利
    public function rebate($invite_code, $userid)
    {
        //查询任务设置
        $task = \app\admin\model\Task::where('id=1')->field('vip,score,money')->find();
        $money = $task['money'];

        Db::startTrans();
        //返利
        $rebate_one = config('site.rebate_one');
        $rebate_two = config('site.rebate_two');
        $rebate_three = config('site.rebate_three');

        //本人增加vip
        Usermodel::where('id', $userid)->setInc('vip_time', $task['vip'] * 86400 + time());
        //三级返利 通过invite_code查出 推荐人的信息
        $user_one = Usermodel::where('number', $invite_code)->field('id,vip_time')->find();
        try {
            if ($user_one) {
                $extensionModel = new Extension();
                //region 一级返利 加分、加钱、加vip
                $find = $extensionModel->where(['userid' => $user_one['id'], 'user_id' => $userid])->find();

                if (!$find) {
                    //没等级
                    if ($user_one['vip_time'] > time()) {
                        //没到期时间
                        $time = $user_one['vip_time'] + $task['vip'] * 86400;
                    } else {
                        //到期时间
                        $time = $task['vip'] * 86400 + time();
                    }
                    Usermodel::where('id', $user_one['id'])->setInc('score', $task['score']);
                    Usermodel::where('id', $user_one['id'])->update(['vip_time' => $time]);
                    Usermodel::where('id', $user_one['id'])->setInc('money', $money * $rebate_one);
                    //保存推广成功后，返佣记录
                    $extensionModel->save(['userid' => $user_one['id'], 'user_id' => $userid, 'cretae_time' => date('Y-m-d H:i:s'), 'money' => $money]);

                } else {
                    throw new Exception('邀请码已用过');
                }
                //endregion
                //region 二级返利  只加钱
                $user_two = Usermodel::where('pid', $user_one['id'])->field('id,vip_time')->find();
                if ($user_two) {
                    Usermodel::where('id', $user_two['id'])->setInc('money', $money * $rebate_two);
                    //保存推广成功后，返佣记录
                    $extensionModel->save(['userid' => $user_two['id'], $user_one['id'], 'cretae_time' => date('Y-m-d H:i:s'), 'money' => $money]);
                }
                //endregion
                //region 三级返利 只加钱
                $user_three = Usermodel::where('pid', $user_two['id'])->field('id,vip_time')->find();
                if ($user_three) {
                    Usermodel::where('id', $user_three['id'])->setInc('money', $money * $rebate_three);
                    //保存推广成功后，返佣记录
                    $extensionModel->save(['userid' => $user_three['id'], $user_two['id'], 'cretae_time' => date('Y-m-d H:i:s'), 'money' => $money]);
                }
                //endregion

                Db::commit();

                $this->success('success');
            } else {
                throw new Exception('邀请码不正确');
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    public function invite()
    {
        $req = $this->request->post();
        $user = $this->auth->getUserinfo();

        if ($user['pid']) {
            $this->error('您已经填过邀请码', null, 100);
        }
        if (empty($req['invite_code'])) {
            $this->error('请输入邀请码', null, 101);
        }

        $pid = Usermodel::where('number', input('invite_code'))->value('id');//邀请人的数据
        if (empty($pid)) {
            $this->error('邀请码不存在', null, 102);
        }

        Usermodel::where('id', $user['id'])->update(['pid' => $pid]);

        $this->rebate($req['invite_code'], $user['id']);


        $this->success('邀请成功');

    }

    //我的余额
    public function money()
    {
        $res = $this->auth->getUserinfo();

        $where['user_id'] = $this->auth->id;
        $where['tong'] = 0;
        $withdraw = \app\admin\model\Withdrawal::where($where)->sum('money');
        $this->result('余额', $res['money']-$withdraw, 200);
    }

    //视频观看次数
    public function leftTimes()
    {
        if (! $this->request->isPost()) {
            $this->error('ＭＵＳＴ　ＢＥ　ＰＯＳＴ');
        }
        $user = $this->auth->getUser();

        $c_num_long = config('site.num_long');
        $num_day = config('site.num_day');
        $c_num_short = config('site.num_short');

        $result = [
            'c_num_long' => $c_num_long,
            'c_num_short' => $c_num_short,
            'num_day' => $num_day,
            'num_short' => $user['num_short'],
            'num_long' => $user['num_long']
        ];
        $this->success('获取成功', $result, 200);
    }

    /** 自动签到
     * @return void
     */
    public function autoSign()
    {

        $leesignModel = model('addons\leesign\model\Leesign');
        $today_start = Date::unixtime("day", 0, 'begin');;
        $ww['uid'] = $this->auth->id;
        $sign_time_where['sign_time'] = ['between', [$today_start, $today_start + 86400]];
        $repeat = $leesignModel->where($sign_time_where)->where($ww)->find();
        if ($repeat) {
            $this->error(__('repeat sign'));
        }

        //签到配置
        $config = get_addon_config('leesign');

        //当月的第一天
        $firstDate = Date::unixtime("month", 0, 'begin');
        //当月的最后一天
        $lastDate = Date::unixtime("month", 0, 'end');

        $w['sign_time'] = ['between', [$firstDate, $lastDate]];
        $w['uid'] = $this->auth->id;

        $signList = $leesignModel->where($w)->order('sign_time desc')->select();
        $len = count($signList, 0);

        if ($signList && $len >= 1) {
            $lianxu = !((date("Y-m-d", $signList[0]['sign_time'] + 86400) != date("Y-m-d", time())));
        } else {
            $lianxu = false;
        }

        //处理逻辑：如果上次签到的日期和这次签到的日期相差不是1天，那么本次签到就不是连续签到。
        $max_sign_num = $lianxu ? $signList[0]['max_sign'] + 1 : 1;

        $score = $config['signnum'];

        //连续签到奖励规则 - 周期奖励
        $zhouqi = $config['types'];

        //当月连续签到所获得的所有额外奖励
        $extra = 0;

        //当天是否触发连续签到的额外奖励
        $extra_reward = 0;

        //开启了连续签到奖励
        if ($config['signstatus'] == 1) {
            //计算连续签到带来的额外奖励
            foreach ($zhouqi as $k => $v) {
                foreach ($signList as $key => $val) {
                    if ($k == $val['max_sign']) {
                        $extra += $v;
                        break;
                    }
                }

                if ($k == $max_sign_num) {
                    $extra_reward += $v;
                }
            }
        }

        $data = [
            'sign_ip' => $this->request->ip(),
            'uid' => $this->auth->id,
            'sign_time' => time(),
            'sign_reward' => $score,
            'sign_extra_reward' => $extra_reward,
            'max_sign' => $max_sign_num
        ];

        if ($leesignModel->insert($data)) {
            //签到积分增加日志
            \app\common\model\User::score($score, $this->auth->id, '连续签到奖励');

            if ($extra_reward > 0) {
                //额外获得积分记录
                \app\common\model\User::score($extra_reward, $this->auth->id, '额外签到奖励');
            }
            $this->success(__('sign success tip', $max_sign_num), ['max_sign' => $max_sign_num, 'month_sign_num' => $len, 'reward' => ($score + $extra_reward)]);
        } else {
            $this->error(__('sign failed'));
        }
    }
    /**
     * 退出登录
     * @ApiMethod (POST)
     */
    public function logout()
    {
        if (!$this->request->isPost()) {
            $this->error(__('Invalid parameters'));
        }
        $this->auth->logout();
        $this->success(__('Logout successful'));
    }

    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @ApiParams (name="avatar", type="string", required=true, description="头像地址")
     * @ApiParams (name="username", type="string", required=true, description="用户名")
     * @ApiParams (name="nickname", type="string", required=true, description="昵称")
     * @ApiParams (name="bio", type="string", required=true, description="个人简介")
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $username = $this->request->post('username');
        $nickname = $this->request->post('nickname');
        $area = $this->request->post('area');
        $mobile = $this->request->post('mobile');
        $bio = $this->request->post('bio');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        if ($username) {
            $exists = \app\common\model\User::where('username', $username)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Username already exists'));
            }
            $user->username = $username;
        }
        if ($nickname) {
            $exists = \app\common\model\User::where('nickname', $nickname)->where('id', '<>', $this->auth->id)->find();
            if ($exists) {
                $this->error(__('Nickname already exists'));
            }
            $user->nickname = $nickname;
        }
        $user->area = $area;
        $user->mobile = $mobile;
        $user->bio = $bio;
        $user->avatar = $avatar;
        $user->save();
        Task::upload($user->id, 3);

        $this->success('sucess');
    }

    /**
     * 修改邮箱
     *
     * @ApiMethod (POST)
     * @ApiParams (name="email", type="string", required=true, description="邮箱")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changeemail()
    {
        $user = $this->auth->getUser();
        $email = $this->request->post('email');
        $captcha = $this->request->post('captcha');
        if (!$email || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        if (\app\common\model\User::where('email', $email)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Email already exists'));
        }
        $result = Ems::check($email, $captcha, 'changeemail');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->email = 1;
        $user->verification = $verification;
        $user->email = $email;
        $user->save();

        Ems::flush($email, 'changeemail');
        $this->success();
    }

    /**
     * 修改手机号
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function changemobile()
    {
        $user = $this->auth->getUser();
        $mobile = $this->request->post('mobile');
        $captcha = $this->request->post('captcha');
        if (!$mobile || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        if (!Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('Mobile is incorrect'));
        }
        if (\app\common\model\User::where('mobile', $mobile)->where('id', '<>', $user->id)->find()) {
            $this->error(__('Mobile already exists'));
        }
        $result = Sms::check($mobile, $captcha, 'changemobile');
        if (!$result) {
            $this->error(__('Captcha is incorrect'));
        }
        $verification = $user->verification;
        $verification->mobile = 1;
        $user->verification = $verification;
        $user->mobile = $mobile;
        $user->save();

        Sms::flush($mobile, 'changemobile');
        $this->success();
    }

    /**
     * 第三方登录
     *
     * @ApiMethod (POST)
     * @ApiParams (name="platform", type="string", required=true, description="平台名称")
     * @ApiParams (name="code", type="string", required=true, description="Code码")
     */
    public function third()
    {
        $url = url('user/index');
        $platform = $this->request->post("platform");
        $code = $this->request->post("code");
        $config = get_addon_config('third');
        if (!$config || !isset($config[$platform])) {
            $this->error(__('Invalid parameters'));
        }
        $app = new \addons\third\library\Application($config);
        //通过code换access_token和绑定会员
        $result = $app->{$platform}->getUserInfo(['code' => $code]);
        if ($result) {
            $loginret = \addons\third\library\Service::connect($platform, $result);
            if ($loginret) {
                $data = [
                    'userinfo'  => $this->auth->getUserinfo(),
                    'thirdinfo' => $result
                ];
                $this->success(__('Logged in successful'), $data);
            }
        }
        $this->error(__('Operation failed'), $url);
    }

    /**
     * 重置密码
     *
     * @ApiMethod (POST)
     * @ApiParams (name="mobile", type="string", required=true, description="手机号")
     * @ApiParams (name="newpassword", type="string", required=true, description="新密码")
     * @ApiParams (name="captcha", type="string", required=true, description="验证码")
     */
    public function resetpwd()
    {
        $type = $this->request->post("type", "mobile");
        $mobile = $this->request->post("mobile");
        $email = $this->request->post("email");
        $newpassword = $this->request->post("newpassword");
        $captcha = $this->request->post("captcha");
        if (!$newpassword || !$captcha) {
            $this->error(__('Invalid parameters'));
        }
        //验证Token
        if (!Validate::make()->check(['newpassword' => $newpassword], ['newpassword' => 'require|regex:\S{6,30}'])) {
            $this->error(__('Password must be 6 to 30 characters'));
        }
        if ($type == 'mobile') {
            if (!Validate::regex($mobile, "^1\d{10}$")) {
                $this->error(__('Mobile is incorrect'));
            }
            $user = \app\common\model\User::getByMobile($mobile);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Sms::check($mobile, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Sms::flush($mobile, 'resetpwd');
        } else {
            if (!Validate::is($email, "email")) {
                $this->error(__('Email is incorrect'));
            }
            $user = \app\common\model\User::getByEmail($email);
            if (!$user) {
                $this->error(__('User not found'));
            }
            $ret = Ems::check($email, $captcha, 'resetpwd');
            if (!$ret) {
                $this->error(__('Captcha is incorrect'));
            }
            Ems::flush($email, 'resetpwd');
        }
        //模拟一次登录
        $this->auth->direct($user->id);
        $ret = $this->auth->changepwd($newpassword, '', true);
        if ($ret) {
            $this->success(__('Reset password successful'));
        } else {
            $this->error($this->auth->getError());
        }
    }
    //个人信息
    public function personal()
    {
        $user = $this->auth->getUserinfo();
        $user = Usermodel::where('id', $user['id'])->find();
        $user = $user->toArray();
        unset($user['password']);
        unset($user['salt']);

        $user['photo'] = Video::where(['user_id' => $user['id'], 'status' => 1, 'class' => '2'])->count();
        $user['video'] = Video::where(['user_id' => $user['id'], 'status' => 1, 'class' => '1'])->count();
        $user['fabu'] = Video::where(['user_id' => $user['id'], 'status' => 1, 'status' => 0])->count();
        $viptime = $user['vip_time'];

        $user['vip_time'] = $viptime ? date('Y-m-d H:i:s', $viptime) : '';

        $arr = \app\common\model\Config::where('name', 'like', '%' . 'score' . '%')->column('value');
        $user['sons_num'] = Usermodel::where('pid', $user['id'])->count();
        if ($user['score'] < $arr[1] && $user['score'] >= $arr[0]) {
            $user['vip'] = 0;
        }
        if ($user['score'] < $arr[2] && $user['score'] >= $arr[1]) {
            $user['vip'] = 1;
        }
        if ($user['score'] >= $arr[2]) {
            $user['vip'] = 2;
        }
        $where['user_id'] = $this->auth->id;
        $where['tong'] = 0;
        $withdraw = \app\admin\model\Withdrawal::where($where)->sum('money');
        $user['money'] -= $withdraw;
        $this->success('个人信息', $user, 200);
    }
    //二维码
    public function qrcode()
    {
        $user = $this->auth->getUserinfo();
        $tma_url = config('site.tma_url');
        $website = config('site.website');

        $user = Usermodel::where('id', $user['id'])->field('avatar,photo,number')->find();
        $user['tma_url'] = $tma_url . '?startapp=' . $user['number'];
        $user['website'] = $website . '?invite_code=' . $user['number'];
        $this->success('推广码', $user, 200);
    }
}
